<template>
	<div class="zh-sensitive">
		<nav-header>
				<div class="zh-h5-nav">
					<div 
						:class="activePanel === 'sensitive' ? 'active' : ''"
						@click="changePanel('sensitive')">敏感词列表</div>
					<div 
						:class="activePanel === 'auth-list' ? 'active' : ''" 
						@click="changePanel('auth-list')">敏感词内容审核</div>
				</div>
		</nav-header>
		<transition name="fade" mode="out-in" v-if="activePanel === 'sensitive'" >
			<div class="zh-table">
				<div class="zh-table-open clear">
					<div class="zh-open-left fl">
						<div class="open-width">
							<el-select v-model="sensitiveDataParam.cateid" filterable placeholder="请选择">
							    <el-option
							      v-for="item in sensitiveCate"
							      :key="item.id"
							      :label="item.name"
							      :value="item.id">
							    </el-option>
							</el-select>
						</div>
						<div class="open-width">
							<el-input 
								v-model="keyword" 
								placeholder="请输入敏感词搜索"
								@keyup.enter.native="searchContent()"
								@keyup.delete.native="changeSearchContent()"></el-input>
						</div>
						<div class="open-width">
							<el-button type="primary" @click="searchContent()">搜索</el-button>
							<el-button type="primary" @click="reset()">重置</el-button>
						</div>
					</div>
					<div class="zh-open-right fr">
						<el-button type="primary" @click="AddSensitiveWords = true">新增敏感词</el-button>
						<el-button type="primary" @click="editSensitiveKeys">编辑敏感词分类</el-button>
					</div>
				</div>
				<div class="zh-table-contents"
					v-loading="loading.status"
		    		:element-loading-text="loading.txt">
					<el-table
					    :data="sensitiveData"
					    border
					    max-height="600"
					    style="width: 100%">
					    <el-table-column
					      type="index"
                :index="typeIndex"
					      label="序号"
					      align="center"
					      show-overflow-tooltip
					      width="50"
					      >
					    </el-table-column>
					    <el-table-column
					      prop="content"
					      label="敏感词"
					      align="center"
					      show-overflow-tooltip
					      >
					    </el-table-column>
					    <el-table-column
					      prop="name"
					      label="敏感词分类"
					      align="center"
					      show-overflow-tooltip
					      >
					    </el-table-column>
					    <el-table-column
					      prop="type"
					      label="敏感词处理"
					      align="center"
					      show-overflow-tooltip
					      >
					    </el-table-column>
					    <el-table-column
					      prop="username"
					      label="配置人账号"
					      align="center"
					      show-overflow-tooltip
					      >
					    </el-table-column>
					    <el-table-column
					      prop="create_time"
					      label="配置时间"
					      align="center"
					      show-overflow-tooltip
					      >
					    </el-table-column>
					    <el-table-column
					      label="操作"
					      align="center">
					      	<template slot-scope="scope">
				      	        <el-button @click="delSensitive(scope.row)" type="text" class="delete-button">删除</el-button>
				      	    </template>
					    </el-table-column>
					</el-table>
					<div class="table-pagination" v-show="total_number > 10">
						<el-pagination
						    @size-change="handleSizeChange"
						    @current-change="handleCurrentChange"
						    :current-page="sensitiveDataParam.page_index"
						    :page-sizes="[10, 20, 30, 40, 50, 100]"
						    :page-size="sensitiveDataParam.page_size"
						    layout="total, sizes, prev, pager, next, jumper"
						    :total="total_number">
						</el-pagination>
						<div class="pagination-button">
							<el-button 
								@click="getList"
								type="primary" icon="el-icon-refresh" 
								circle title="刷新数据" size="mini" >
							</el-button>
						</div>
					</div>
				</div>
				<!-- 新增敏感词 -->
				<el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="新增敏感词" :visible.sync="AddSensitiveWords" class="addSensitive" width="400px">
					<el-form :model="addForm" ref="addForm" :rules="rules" status-icon label-position="left" label-width="100px">
					    <el-form-item label="敏感词" prop="content" :rules="[
		      				{ required: true, validator: validateInput, message: '请输入敏感词', trigger: 'blur' },
						]">
					      	<el-input 
					      		v-model="addForm.content" 
					      		placeholder="请输入敏感词（10个字符）" 
					      		autocomplete="off" 
					      		:maxlength="parseInt(10)"
					      		clearable>
					      	</el-input>
					    </el-form-item>
					    <el-form-item label="分类" prop="cate_id" :rules="[{required: true,message: '请选择分类'}]">
					      	<el-select v-model="addForm.cate_id" filterable placeholder="请选择分类">
                                <template v-for="item in sensitiveCate">
                                    <el-option 
                                        v-if="parseInt(item.id)>0"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                </template>
					      	</el-select>
					    </el-form-item>
					    <el-form-item label="敏感词处理" prop="type" :rules="[{required: true,message: '请选择敏感词处理'}]">
					      	<el-select v-model="addForm.type" filterable @change="showReplaceCheck" placeholder="请选择敏感词处理">
					        	<el-option label="审核敏感词" value="2"></el-option>
					        	<el-option label="替换敏感词" value="1"></el-option>
					        	<el-option label="禁止敏感词" value="0"></el-option>
					      	</el-select>
					    </el-form-item>
					    <el-form-item label="替换敏感词" prop="replace_content" v-if="showReplace">
							<el-input 
					      		v-model="addForm.replace_content" 
					      		placeholder="请输入敏感词（10个字符）" 
					      		autocomplete="off" 
					      		:maxlength="parseInt(10)"
					      		clearable>
					      	</el-input>
					    </el-form-item>
					</el-form>
					<div slot="footer" class="dialog-footer">
						<el-button  @click="AddSensitiveWords = false">取消</el-button>
					    <el-button type="primary" @click="addSensitive">确定</el-button>
					</div>
				</el-dialog>
				<!-- 编辑敏感词 -->
				<el-dialog 
                    :close-on-click-modal="false" 
                    :close-on-press-escape="false" 
                    :before-close="cancelEdit" 
                    :visible.sync="EditSensitiveWords" 
                    class="editSensitive" 
                    title="编辑敏感词分类" 
                    width="500px">
					<el-form :model="editForm" ref="editForm" :rules="rules" status-icon label-position="left" label-width="100px">
					    <el-form-item label="分类名称" class="fromWidth" prop="temp_cate_name">
					      	<el-input 
					      		v-model="editForm.temp_cate_name" 
					      		placeholder="请输入分类名称（10个字符）" 
					      		autocomplete="off" 
					      		:maxlength="parseInt(10)"
					      		clearable>
					      	</el-input>
					      	<el-button type="primary" @click="addSensitiveCate">添加</el-button>
					    </el-form-item>
					    <el-form-item label="敏感词分类">
					      	<el-tag
					      	  :key="inx"
					      	  v-for="(item,inx) in sensitiveCateTag"
					      	  closable
					      	  :disable-transitions="false"
					      	  @close="delSensitiveCate(inx)">
					      	  {{item.name}}
					      	</el-tag>
					    </el-form-item>
					</el-form>
					<div slot="footer" class="dialog-footer">
						<el-button @click="cancelEdit">取消</el-button>
					    <el-button type="primary" @click="saveSensitiveCate">保存</el-button>
					</div>
				</el-dialog>
			</div>
		</transition>
		<transition name="fade" mode="out-in" v-if="activePanel === 'auth-list'" >
			<zh-sensitive-content />
		</transition>
	</div>
</template>
<script>
  	export default {
	    data() {
		    return {
		    	activePanel: 'sensitive',
				loading:{
					status:false,
					txt:'获取数据...',
				},
		        sensitiveCate: [],
		        sensitiveCateTag:[],
		        sensitiveData:[],
		        sensitiveDataParam:{
		        	cateid: 0,
		       		keyword: '',
		       		page_index:1,
		       		page_size:10
				},
				keyword: '',
		        showReplace:false,
		        
                total_number: 0,//共几条
                AddSensitiveWords: false,
                addForm: {
                	user_id:this.$g.user_id,
                  	type: '',
                  	cate_id:'',
                  	content:'',
                  	replace_content:'',
                },

                EditSensitiveWords: false,
                editForm: {
                  	temp_cate_name: '',
                },

                rules: {
                	temp_cate_name :[
						{ required: true, validator: this.validateInput, message: '请输入分类名称', trigger: 'blur' },
						{ min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
					],
                },

                
		    }
		},
		created(){
	    	this.toggleView();
	    	this.getSensitiveCate();
	    	this.getList();
	    },
	    watch:{
	    	$route(){
	    		this.toggleView()
	    	},
	    	AddSensitiveWords(){
	    		if(this.AddSensitiveWords === false) {
	    			this.$refs.addForm.resetFields()
	    		}
	    	},
	    	EditSensitiveWords(){
	    		if(this.AddSensitiveWords === false) {
	    			this.editForm.temp_cate_name = ''
                }
	    	}
	    },
		methods: {
            /**
             * 编辑敏感词
             */
            editSensitiveKeys() {
                this.EditSensitiveWords = true;
                let _obj = this.sensitiveCate.filter(item => {
                    return item.id != 0;
                })
                this.sensitiveCateTag = deep_clone(_obj);
            },
			cancelEdit() {
				this.$refs.editForm.clearValidate();
				this.EditSensitiveWords = false;
				this.editForm.temp_cate_name = '';
			},
			validateInput(rule, value, callback){/*校验输入内容是否为空 */
				if ( is_empty(value) ) {
					return callback(new Error('请输入分类名称'));
				} else {
					callback()
				}
			},
			changePanel(panel){
				this.activePanel = panel;
			},
			// 序号
            typeIndex(index) {
                return index + (this.sensitiveDataParam.page_index - 1) * this.sensitiveDataParam.page_size + 1;
            },
			
			checkChange(rule, value, callback){
                if (!isEmpty(value)) {
                    return callback(new Error('请选择选项'));
                }else{
                    callback()
                }
            },
			// 搜索
			searchContent(){
				this.sensitiveDataParam.page_index = 1
				this.sensitiveDataParam.keyword = this.keyword;
				this.getList()
            },
            /**
             * 重置搜索条件
             */
			reset() {
                this.sensitiveDataParam.cateid = 0;
				this.sensitiveDataParam.page_index = 1;
				this.sensitiveDataParam.page_size = 10;
				this.sensitiveDataParam.keyword = '';
				this.keyword = '';
				this.getList()
			},
	    	changeSearchContent(){
	    		if(this.sensitiveDataParam.keyword == ''){
        			this.sensitiveDataParam.page_index = 1
					this.getList()
        		}
	    	},
			//记录导航状态
		    toggleView(){
		   		this.view = this.$route.name
		    },
		    // 分页
		    handleSizeChange(val) {
		    	this.sensitiveDataParam.page_index = 1;
		    	this.sensitiveDataParam.page_size = val;
		    	this.getList();
		    },
		    handleCurrentChange(val) {
		        this.sensitiveDataParam.page_index = val;
		        this.getList();
		    },
		    addSensitiveCate(){
		    	this.$refs['editForm'].validate((valid) => {
					if (valid) {
						if( this.sensitiveCateTag.length >= 12) {
				    		return this.$message.error('分类添加超过最大限制数12个');
				    	}
				    	for (var i = this.sensitiveCateTag.length - 1; i >= 0; i--) {
				    		if( this.sensitiveCateTag[i].name == this.editForm.temp_cate_name ){
				    			return this.$message.error('分类名称不能重复添加');
				    		}
				    	}
				    	this.sensitiveCateTag.push({i_s:0,name:this.editForm.temp_cate_name,id:0});
				    	this.$refs.editForm.resetFields()// 清除表单验证
					} else {
						return false;
					}
				});
		    	
		    },
		    delSensitiveCate(tag) {
		    	if( parseInt( this.sensitiveCateTag[tag].i_s )  === 1 ){
		    		this.$message.error('该分类下存在敏感词，不能删除');
		    		return false;
		    	}
	            this.sensitiveCateTag.splice(tag, 1);
	        },
	        saveSensitiveCate(){
	        	// 重写成功回调
				let success = ( data => {
					this.$message.success(data.msg);
					this.EditSensitiveWords = false
					this.getSensitiveCate();
				});
  				this.$ajax.post('/api/setting/sensitive_cate',this.sensitiveCateTag,{func:{success:success}})
	        },
	        //敏感词分类
			getSensitiveCate(){
				// 重写成功回调
				let success = ( data => {
					this.sensitiveCateTag = deep_clone( data.data );
					this.sensitiveCate = data.data;
					this.sensitiveCate.unshift({id:0,name:"全部分类"});
				});
  				this.$ajax.get('api/setting/sensitive_cate',{func:{success:success}});
			},
			//敏感词分类
			getList(){
				this.loading.status = true;
				// 重写成功回调
				let success = ( data => {
					this.loading.status = false;
					this.sensitiveData = data.data.data;
					this.total_number = data.data.data_sum;
				});
				let fail = ( data => {
					this.$message.error(data.msg)
					this.loading.status = false;
				})
  				this.$ajax.get('api/setting/sensitive_data',{params:this.sensitiveDataParam,func:{success:success,fail:fail}})
			},
			// 删除
			delSensitive(id){
				this.$confirm("即将删除“" + id.content + "”且无法恢复，确认删除吗？", "删除", { type: 'warning'}).then(() => {
					// 重写成功回调
					let success = ( data => {
					if (this.sensitiveData.length - 1 === 0) {
						if (this.sensitiveDataParam.page_index > 1) {
							this.sensitiveDataParam.page_index--;
						} else {
							this.sensitiveDataParam.page_index = 1;
						}
					}
						
						this.getList();
					});
	  				this.$ajax.delete('api/setting/sensitive',{params:{id:id.id},func:{success:success}})
	  			}).catch(() => {
                    this.$message.info("已取消删除操作！")
                });
			},
			addSensitive(){
				this.$refs.addForm.validate((valid) => {
	     			if (valid) {
						// 重写成功回调
						let success = ( data => {
							this.AddSensitiveWords = false
							this.$message.success(data.msg);
							this.getList();
							this.$refs.addForm.resetFields()//清空表单
						});
		  				this.$ajax.post('api/setting/sensitive',this.addForm,{func:{success:success}})
		  			} else {
		  				return false
		  			}
		  		});
			},
			showReplaceCheck( type ){
				if( parseInt( type ) === 1 ) {
					this.showReplace = true;
				}else{
					this.showReplace = false;
					this.addForm.replace_content = '';
				}
			}
		},
  	}
</script>
<style lang="scss">
	.zh-sensitive {
		.el-table__body-wrapper table tbody {
			td:nth-child(7) {
				padding: 0;
			}
		}
		.editSensitive {
			.fromWidth {
				.el-input {
					width: 220px;
				}
				.el-button {
					min-width: 80px;
					margin-left: 8px;
				}
			}
			.el-tag {
			    margin-right: 10px;
			}
		}
	}
</style>

